<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\ShopProduct\ShopProductBaseAction;
use App\Admin\Actions\ShopProduct\ShopProductDiscountAction;
use App\Admin\Actions\ShopProduct\ShopProductSaleAction;
use App\Admin\Actions\ShopProduct\ShopProductActiveAction;
use App\Admin\Actions\ShopProduct\ShopProductRecommendAction;
use App\Admin\Actions\ShopProduct\ShopProductCateAction;
use App\Admin\Actions\ShopProduct\ShopProductCopyAction;
use App\Admin\Actions\ShopProduct\ShopProductDeleteAction;
use App\Admin\Actions\ShopProduct\ShopProductDownStatusAction;
use App\Admin\Actions\ShopProduct\ShopProductEditAction;
use App\Admin\Actions\ShopProduct\ShopProductRefreshAction;
use App\Admin\Actions\ShopProduct\ShopProductSetAgentAction;
use App\Admin\Actions\ShopProduct\ShopProductSortAction;
use App\Admin\Actions\ShopProduct\ShopProductSubPriceAction;
use App\Admin\Actions\ShopProduct\ShopProductUpStatusAction;
use App\Admin\Grid\NGrid;
use App\Admin\Grid\Tools\ShopProduct\AddAnimalShopProductTools;
use App\Admin\Grid\Tools\ShopProduct\AddFeedShopProductTools;
use App\Admin\Grid\Tools\ShopProduct\AllShopProductTools;
use App\Admin\Grid\Tools\ShopProduct\DeleteShopProductTools;
use App\Admin\Grid\Tools\ShopProduct\UnSaleShopProductTools;
use App\Admin\Grid\Tools\ShopProduct\UpShopProductTools;
use App\Admin\Grid\Tools\ShopProduct\DownShopProductTools;
use App\Admin\Grid\Tools\ShopProduct\SaleShopProductTools;
use App\Library\Logic\ActivityZoneLogic;
use App\Library\Logic\InviteCertificationLogic;
use App\Library\Logic\ShopProductSpecsLogic;
use App\Library\Logic\ShopUserLogic;
use App\Library\Models\AdminShopProductModel;
use App\Library\Traits\AdminControllerTrait;
use App\Models\SystemConfigModel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Grid\Filter;
use Encore\Admin\Grid\Tools;
use Encore\Admin\Grid\Tools\BatchActions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Table;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class ShopProductController extends AdminController
{
    use AdminControllerTrait;

    protected $title = '商品';

    public function paging(Content $content): Content
    {
        return $content->title($this->title())->description($this->description['index'] ?? trans('admin.list'))
            ->body(view('product.paging', [
                'newAuth' => aesEncrypt(encodeId(Admin::user()->user_id)),
            ]));
    }

    /**
     * grid
     * @return NGrid
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    protected function grid(): NGrid
    {
        $userId = Admin::user()->user_id;

        $grid = new NGrid(new AdminShopProductModel);
        $grid->model()->where('plug', 0)->where('plug2', 0)
            ->where(function ($query) {
                if (!empty(Admin::user()->admin_type)) {
                    $mainId = Admin::user()->user_main_id;
                    $userIdArr[] = Admin::user()->user_id;
                    if (!empty($mainId)) {
                        $userIdArr = DB::table('shop_user')
                            ->where('user_main_id', $mainId)->pluck('user_id')->toArray();
                        $userIdArr[] = $mainId;
                    }
                    $query->whereIn('shop_product.user_id', $userIdArr);
                }
            })
            ->with('specs')
            ->orderByDesc('product_status')->orderByDesc('status_recommend')->orderBy('sort');
        $status = request()->get('status');
        if (!is_null($status)) {
            $status = match ((int)$status) {
                0 => 1,
                1 => 2,
                default => -1
            };
            $grid->model()->where('product_status', $status);
        }
        $grid->filter(function (Filter $filter) {
            $filter->disableIdFilter();
            $filter->column(1 / 2, function (Filter $filter) {
                $filter->equal('product_id', 'ID')->integer();
                $filter->equal('product_category_id_1', '一级分类')->select(__('base.cate'));
                $oneCate = request()->get('product_category_id_1');
                $filter->equal('product_category_id_2', '二级分类')
                    ->select($oneCate > 0 ? '/admin/ajax/category?q=' . $oneCate : null);
                $twoCate = request()->get('product_category_id_2');
                $filter->equal('product_category_id_3', '三级分类')
                    ->select($twoCate > 0 ? '/admin/ajax/category?q=' . $twoCate : null);
//                $filter->equal('buy_will', '随手买')->select(__('l.whether'));
            });
            $filter->column(1 / 2, function (Filter $filter) {
                $filter->like('serial_number', __('l.serialNumber'));
                $filter->like('product_name', '名称');
                $filter->equal('status_recommend', __('shop_product.statusRecommend'))->select(__('l.whether'));
                $filter->equal('is_agent', __('shop_product.is_agent'))->select(__('shop_product.isAgentArr'));
                $filter->where(function ($query) {
                    $query->where('is_agent', 0);
                    if ((int)$this->input === -1) {
                        $query->where('product_category_id_2', 23)->where('product_category_id_3', '<>', 24);
                    } else if ((int)$this->input === 23) $query->where('product_category_id_3', 24);
                    else $query->where('product_category_id_2', $this->input);
                }, '类别')->select(__('shop_product.cateArr'));
            });
        });
        $list = DB::table('shop_category')->pluck('category_name', 'category_id')->toArray();
        $grid->column('product_id', 'ID')->sortable();
        $grid->column('serial_number', __('l.serialNumber'));
        $grid->column('sort', __('l.sort'))->sortable();
        $grid->column('product_status', '状态')->using([1 => '下架', 2 => '上架']);
        $grid->column('status_recommend', '推荐')->using(__('l.whether'));
        $grid->column('cate', '类别')->display(function () {
            if ($this->is_agent === 1) return null;
            else if ($this->product_category_id_2 === 37) return __('shop_product.cateArr')[37];
            else if ($this->product_category_id_2 === 32) return __('shop_product.cateArr')[32];
            else if ($this->product_category_id_2 === 41) return __('shop_product.cateArr')[41];
            else if ($this->product_category_id_2 === 23) {
                if ($this->product_category_id_3 === 24) return __('shop_product.cateArr')[23];
                else return __('shop_product.cateArr')[-1];
            } else return null;
        });
        $grid->column('product_avatar', '主图')->display(function ($column) {
            if (!is_null($column)) return view('image', ['id' => $this->product_id, 'image' => fileIdToUrl($column)]);
            else return null;
        });
        $grid->column('product_name', '名称')->display(function ($column) {
            if (strlen($column) > 20) return mb_substr($column, 0, 20) . '...';
            else return $column;
        });
        $grid->column('product_category', '商品分类')->display(function () use ($list) {
            return implode('-', [
                $list[$this->product_category_id_1] ?? null,
                $list[$this->product_category_id_2] ?? null,
                $list[$this->product_category_id_3] ?? null
            ]);
        });
        $grid->column('spec_price', '销售价格')->display(function () {
            return view('product.spec.edit_price', [
                'id' => $this->product_id,
                'newAuth' => aesEncrypt(encodeId(Admin::user()->user_id)),
                'priceSection' => priceSection($this->specs),
                'specs' => $this->specs,
                'defaultImg' => __('com.defaultImg'),
                'serialNumber' => $this->serial_number,
                'status' => $this->product_status,
                'subPrice' => $this->sub_price,
                'plug' => $this->plug,
            ]);
        });
        $grid->column('spec_edit', '总库存')->display(function () {
            return view('product.spec.edit_stock', [
                'stock' => array_sum(array_column($this->specs->toArray(), 'ps_usable_stock')),
                'id' => $this->product_id,
                'newAuth' => aesEncrypt(encodeId(Admin::user()->user_id)),
                'specs' => $this->specs,
                'defaultImg' => __('com.defaultImg'),
                'serialNumber' => $this->serial_number,
                'status' => $this->product_status,
                'plug' => $this->plug,
            ]);
        });
        $specColumns = $this->specColumns();
        $grid->column('spec', '规格')->expand(function ($model) use ($specColumns) {
            return new Table(array_values($specColumns), $model->specs->map(function ($spec) use ($specColumns) {
                if (!empty($spec->ps_avatar)) $spec->fileUrl = view('image', [
                    'id' => $spec->serial_number,
                    'size' => 50,
                    'image' => fileIdToUrl($spec->ps_avatar)
                ]);
                return $spec->only(array_keys($specColumns));
            })->toArray());
        })->style('text-align:center');
        $grid->column('sales', __('l.sales'));
        $grid->column('is_agent', __('shop_product.is_agent'))->using(__('shop_product.isAgentArr'))->label(__('l.openArrLabel'));
        //$grid->column('plug', __('shop_product.plug'))->using(__('shop_product.plugArr'))->label(__('l.openArrLabel'));
        $grid->column('product_note', __('shop_product.product_note'))->display(function () {
            if (is_null($this->product_note)) return '';
            return view('product.product_note', [
                'id' => $this->product_id,
                'productNote' => $this->product_note,
            ]);
        });
        $grid->column('operated_at', __('l.operatedAt'))->sortable();
        $grid->actions(function (Actions $action) use ($userId) {
            $action->disableDelete();
            $action->disableEdit();
            if ($action->row->product_status === 1) {
                if ($userId === config('app.superId') || $userId === $action->row->user_id) {
                    $action->add(new ShopProductEditAction);
                }
            }
            if ($action->row->product_status === 1) {
                $action->add(new ShopProductUpStatusAction);
                $action->add(new ShopProductDeleteAction);
            } else $action->add(new ShopProductDownStatusAction);
            $action->add(new ShopProductRecommendAction($this->row->status_recommend));
            $action->add(new ShopProductRefreshAction);
            if ($userId == config('app.superId')) $action->add(new ShopProductCopyAction);
            $action->add(new ShopProductSaleAction);
            $action->add(new ShopProductActiveAction);
            $action->add(new ShopProductCateAction);
            $action->add(new ShopProductDiscountAction);
            $action->add(new ShopProductSubPriceAction);
            $action->add(new ShopProductBaseAction);
            $action->add(new ShopProductSetAgentAction($action->row->is_agent));
            $action->add(new ShopProductSortAction);
        });
        $grid->disableActions(false);
        $grid->disableRowSelector(false);
        $grid->batchActions(function (BatchActions $batch) {
            $batch->disableDelete();
        });
        $grid->tools(function (Tools $tools) use ($status) {
            $collection = AdminShopProductModel::query()->where('plug', 0)->where('plug2', 0)->groupBy('product_status')
                ->where(function ($query) {
                    if (!empty(Admin::user()->admin_type)) {
                        $mainId = Admin::user()->user_main_id;
                        $userIdArr[] = Admin::user()->user_id;
                        if (!empty($mainId)) {
                            $userIdArr = DB::table('shop_user')
                                ->where('user_main_id', $mainId)->pluck('user_id')->toArray();
                            $userIdArr[] = $mainId;
                        }
                        $query->whereIn('user_id', $userIdArr);
                    }
                })
                ->pluck(DB::raw('count(*) as count'), 'product_status');
            $tools->append(new AllShopProductTools($status ?? 0));
            $tools->append(new SaleShopProductTools($collection[2] ?? 0, $status ?? 0));
            $tools->append(new UnSaleShopProductTools($collection[1] ?? 0, $status ?? 0));
            $tools->append(new DeleteShopProductTools);
            $tools->append(new UpShopProductTools);
            $tools->append(new DownShopProductTools);
            $tools->append(new AddFeedShopProductTools);
            $tools->append(new AddAnimalShopProductTools);
        });
        return $grid;
    }

    /**
     * detail
     * @param int $id
     * @return Show
     */
    protected function detail(int $id): Show
    {
        $show = new Show(AdminShopProductModel::findOrFail($id));
        $show->field('product_id', 'ID');
        $show->field('serial_number', __('l.serialNumber'));
        $show->field('user_id', '卖家');
        $show->field('product_status', __('l.status'))->using([1 => '下架', 2 => '上架']);
        $show->field('product_name', '名称');
        $show->field('product_category_id_1', '商品分类')->as(function ($field) {
            $list = DB::table('shop_category')->pluck('category_name', 'category_id')->toArray();
            return implode('-', [$list[$field], $list[$this->product_category_id_2], $list[$this->product_category_id_3]]);
        });
        $show->field('product_stock_empty', __('shop_product.product_stock_empty'))->using(__('shop_product.stockArr'));
        $show->field('product_activity', '活动')->as(function ($activity) {
            return $activity === 1 ? '参与' : '无';
        });
        $show->field('product_activity_type', __('shop_product.product_activity_type'))
            ->using(ActivityZoneLogic::query()->pluck('title', 'id')->toArray());
        $show->field('product_brand', '品牌')->as(function ($brand) {
            return empty($brand) ? '无' : $brand;
        });
        $show->field('add_user_id', '添加人');
        $show->field('edit_user_id', '编辑人');
        $show->field('main_img_ids', '主图')->unescape()->as(function ($column) {
            if (empty($column)) return null;
            $arr = [];
            foreach (explode(',', $column) as $v) $arr[] = fileIdToUrl($v);
            return $arr;
        })->carousel();
        $show->field('desc_img_ids', '详情图')->unescape()->as(function ($column) {
            if (empty($column)) return null;
            $arr = [];
            foreach (explode(',', $column) as $v) $arr[] = fileIdToUrl($v);
            return $arr;
        })->carousel();
        $show->field('specs', '销售价格')->as(function ($specs) {
            return priceSection($specs);
        });
        $show->field('sub_price', '按件满减')->as(function ($subPrice) {
            return $subPrice > 0 ? $subPrice : '未设置';
        });
        $show->field('product_avatar_img_id_json', __('shop_product.product_avatar_img_id_json'));
        $show->field('product_protect', __('shop_product.product_protect'));
        $show->field('product_wild_care', __('shop_product.wildCare'))->using(__('shop_product.wildCareArr'));
        $show->field('product_stage', __('shop_product.stage'))->using(__('shop_product.stageArr'));
        $show->field('product_gene', __('shop_product.gene'));
        $show->field('product_label', __('l.tag'));
        $show->field('product_online_time', __('shop_product.product_online_time'))->as(function ($field) {
            return $field > 0 ? now()->timestamp($field) : null;
        });
        $show->field('product_offline_time', __('shop_product.product_offline_time'))->as(function ($field) {
            return $field > 0 ? now()->timestamp($field) : null;
        });
        $show->field('product_effective_day', __('shop_product.product_effective_day'));
        $show->field('product_effective_time', __('shop_product.product_effective_time'));
        $show->field('product_special_start_time', __('shop_product.product_special_start_time'));
        $show->field('product_special_end_time', __('shop_product.product_special_end_time'));
        $show->field('product_hits', __('shop_product.product_hits'));
        $show->field('product_note', __('shop_product.product_note'));
        $show->field('product_feed_hd_id', __('shop_product.product_feed_hd_id'));
        $show->field('product_tool_effect', __('shop_product.product_tool_effect'));
        $show->field('product_tool_species', __('shop_product.product_tool_species'));
        $show->field('product_tool_stage', __('shop_product.product_tool_stage'));
        $show->field('product_content', __('shop_product.product_content'));
        $show->field('product_content_img_id_json', __('shop_product.product_content_img_id_json'));
        $show->field('ps_id_json', __('shop_product.ps_id_json'));
        $show->field('status_recommend', '推荐')->using(__('l.whether'));
        $show->field('product_pet_code', __('shop_product.product_pet_code'));
        $show->field('spec_json', '规格');
        $show->field('publish_at', '发布日期');
        $show->field('created_time', '创建日期');
        $show->field('operated_at', '操作时间');
        $show->field('sales', '销量');
        $show->field('created_at', __('l.createdAt'));
        $show->field('updated_at', __('l.updatedAt'));
        return $show;
    }

    /**
     * hiddenForm
     * @return Form
     */
    protected function hiddenForm(): Form
    {
        $form = new Form(new AdminShopProductModel);
        $form->hidden('product_id');
        $form->hidden('main_img_ids');
        $form->hidden('desc_img_ids');
        $form->hidden('video_id');
        $form->hidden('ps_id_json')->required();
        $form->hidden('spec_json')->required();
        $form->hidden('product_avatar');
        $form->hidden('ossPrefix')->default(config('oss.url'));
        $form->hidden('publish_at');
        if ($form->isCreating()) {
            $form->hidden('serial_number');
            $form->hidden('add_user_id')->default(Admin::user()->user_id);
            $form->hidden('user_id')->default(Admin::user()->user_id);
            $form->hidden('created_time');
        }
        $form->ignore(['ossPrefix']);
        return $form;
    }

    /**
     * item
     * @param Form $form
     * @param string $type
     * @return Model|null
     */
    protected function item(Form $form, string $type = 'animal'): ?Model
    {
        $item = null;
        if ($form->isEditing()) {
            $id = request()->route()->parameters()['id'] ?? request()->route()->parameters()['shopProduct' . ucfirst($type)];
            $item = AdminShopProductModel::query()->find($id);
        }
        return $item;
    }

    /**
     * leftColumn
     * @param Form $form
     * @param Model|null $item
     * @param array $two
     * @param int $flag
     * @return void
     */
    protected function leftColumn(Form $form, ?Model $item, array $two, int $flag = 0): void
    {
        $form->column(1 / 2, function (Form $form) use ($item, $two, $flag) {
            $form->display('mainImgIds', __('l.mainImgIds'))->with(function () use ($item) {
                return view('upload_main_imgs', [
                    'mainImgStr' => AdminShopProductModel::mainImgStr($item),
                ]);
            });
            //$defaultTwo = !is_null($item) ? $item->product_category_id_2 : ($flag === 0 ? 3 : 23);
            $defaultTwo = !is_null($item) ? $item->product_category_id_2 : 59;

            $form->select('product_category_id_2', '商品类目')->default($defaultTwo)->options($two)->load('product_category_id_3', '/admin/ajax/category')->required();
            $form->text('product_name', __('l.title'))->attribute('maxlength', 30)->required()->default(random())->rules('required');
            $form->select('product_activity', __('shop_product.activity'))->options(__('shop_product.whether'));
            if ($flag === 0) {
                $form->select('product_protect', __('shop_product.product_protect'))->options(['否', '是']);
            }
            $form->select('product_brand', __('l.brand'))->options([
                null,
                null => '无',
                '海岛鬃狮' => '海岛鬃狮'
            ])->default(null);
            $form->datetime('product_special_start_time', __('shop_product.product_special_start_time'));
            if ($flag === 0) {
                $form->tags('product_gene', __('shop_product.gene'))->options(explode(',', __('shop_product.geneStr')));
            } else $form->text('product_tool_stage', __('shop_product.product_tool_stage'));
            $form->textarea('product_note', __('shop_product.product_note'));
            $form->display('descImgIds', __('l.descImgIds'))->with(function () use ($form, $item) {
                return view('upload_desc_imgs', [
                    'descImgStr' => AdminShopProductModel::descImgStr($item),
                ]);
            });
        });
    }

    /**
     * rightColumn
     * @param Form $form
     * @param Model|null $item
     * @param array $three
     * @param int $flag
     * @return void
     */
    protected function rightColumn(Form $form, ?Model $item, array $three, int $flag = 0): void
    {
        $form->column(1 / 2, function (Form $form) use ($item, $three, $flag) {
            $form->display('video', __('l.video'))->with(function () use ($item, $three) {
                return view('upload_video', [
                    'videoStr' => AdminShopProductModel::videoStr($item),
                ]);
            });
            //$defaultThree = !is_null($item) ? $item->product_category_id_3 : ($flag === 0 ? 7 : 26);
            $defaultThree = !is_null($item) ? $item->product_category_id_3 : 70;
            $form->select('product_category_id_3', '子类目')->default($defaultThree)->options($three)->required()->rules('required');
            $form->tags('product_label', __('l.tag'));
            $form->select('product_activity_type', __('shop_product.product_activity_type'))
                ->options(ActivityZoneLogic::query()->pluck('title', 'id')->toArray());
            if ($flag === 0) {
                $form->select('product_wild_care', __('shop_product.wildCare'))->options(__('shop_product.wildCareArr'));
                $form->select('product_stage', __('shop_product.stage'))->options(__('shop_product.stageArr'));
            } else {
                $form->text('product_tool_species', __('shop_product.product_tool_species'))->attribute('maxlength', 30);
            }
            $form->datetime('product_special_end_time', __('shop_product.product_special_end_time'));
            $form->select('product_status', __('shop_product.productStatus'))->default(2)->options(__('shop_product.productStatusArr'))->required();
            $form->textarea('product_content', __('shop_product.product_content'));
            $config = SystemConfigModel::query()->where('id', 1)->value('content');
            $classList = Arr::get($config, 'jlTag');

            //$classList = array_column($classList,'contet');
            $form->select('plug', __('shop_product.plug'))->options($classList);
        });
    }

    /**
     * leftColumn
     * @param Form $form
     * @param Model|null $item
     * @return void
     */
    protected function specColumn(Form $form, ?Model $item): void
    {
        $form->column(12, function (Form $form) use ($item) {
            $form->display('spec', '规格')->with(function () use ($item) {
                return view('product.spec.detail_edit', [
                    'item' => $item,
                    'certification' => InviteCertificationLogic::check(Admin::user()->user_id),
                    'newAuth' => aesEncrypt(encodeId(Admin::user()->user_id)),
                    'specListStr' => is_null($item) ? '' : json_encode($item->specs),
                ]);
            })->required();
        });
    }

    /**
     * savingForm
     * @param Form $form
     * @return void
     */
    protected function savingForm(Form $form): void
    {
        $form->saving(function (Form $form) {
            if (is_null($form->ps_id_json)) return $this->backWith('请选择规格');
            else if (is_null($form->product_category_id_2)) return $this->backWith('请选择商品类目');
            //else if (is_null($form->product_category_id_3)) return $this->backWith('请选择子类目');
            else if (!is_null($form->model()->product_id)) {
                if ($form->model()->product_status === 2) return $this->backWith('请先下架商品');
            }
            if ($form->plug > 0) {
                if (is_null($form->product_special_start_time)) return $this->backWith('捡漏商品必须设置优惠时间');
                else if ($form->product_special_start_time <= now()->toDateTimeString()) return $this->backWith('优惠时间必须是未来时间');
                else if ($check = ShopProductSpecsLogic::plugCheck($form->spec_json)) return $this->backWith($check);
            }
            if (is_null($form->product_activity)) $form->product_activity = 0;
            if (is_null($form->product_activity_type)) $form->product_activity_type = 0;
            if (is_null($form->product_wild_care)) $form->product_wild_care = 0;
            if (is_null($form->product_stage)) $form->product_stage = 0;
            if (is_null($form->plug)) $form->plug = 0;
            if ($form->product_status == 2) $form->publish_at = now()->toDateString();
            $form->updated_at = now()->timestamp;
            if ($form->isCreating()) {
                $form->created_time = now()->toDateString();
                $form->serial_number = AdminShopProductModel::getSerialNumber();
            }
            if (is_null($form->main_img_ids)) {
                $form->main_img_ids = __('com.defaultImg');
                $form->product_avatar = __('com.defaultImg');
            } else $form->product_avatar = explode(',', $form->main_img_ids)[0];
            if ((int)$form->product_category_id_3 === 24) {
                $form->product_activity = 1;
                $form->product_activity_type = 4;
            }
            return null;
        });
    }

    /**
     * savedForm
     * @param Form $form
     * @return void
     */
    protected function savedForm(Form $form): void
    {
        $form->saved(function (Form $form) {
            if (is_null($form->ps_id_json)) {
                $userId = Admin::user()->user_id;
                $userMainId = ShopUserLogic::valueByWhere('userId', $userId, 'userMainId');
                $spec = ShopProductSpecsLogic::insertForModel([
                    'productId' => $form->model()->product_id,
                    'randProductId' => 0,
                    'userId' => is_null($userMainId) || $userMainId === 0 ? $userId : $userMainId,
                    'ps_name' => '默认',
                    'psPriceUnderlined' => 0.01,
                ]);
                $form->model()->ps_id_json = $spec->ps_id;
                $form->model()->spec_json = $spec->serial_number;
                $form->model()->save();
                cache(['shopProductSpec:' . $spec->serial_number => $spec->ps_id]);
            } else {
                ShopProductSpecsLogic::query()
                    ->whereIn('ps_id', explode(',', $form->ps_id_json))
                    ->update(['product_id' => $form->model()->product_id]);
            }
            mq('shopProductChange', $form->model());
            sleep(1);
        });
        $form->setWidth(10);
    }

    private function specColumns(): array
    {
        return [
            'ps_id' => 'ID',
            'serial_number' => '序列号',
            'fileUrl' => '图片',
            'ps_name' => '名称',
            'ps_price' => '优惠价格',
            'ps_price_underlined' => '原价',
            'ps_total_stock' => '总库存',
            'ps_usable_stock' => '可用库存',
            'ps_disable_stock' => '不可用库存',
            'ps_buy_limit' => '限购数量',
            'sales' => '销量',
//            'commission' => '佣金',
//            'commission_ratio' => '佣金比例',
//            'buy_will_price' => '随手买',
        ];
    }
}
